package de.voicegym.voicegym.menu.settings

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.MenuItem
import androidx.preference.*
import de.voicegym.voicegym.R

class SettingsFragment : PreferenceFragmentCompat() {

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {

        // find all preferences in the xml layout file - see for all preferences
        addPreferencesFromResource(R.xml.pref_fourier_instrumentview)
        setHasOptionsMenu(true)

        // bind these preference keys  and set onChangeListeners when their values are changed
        bindPreferenceSummaryToValue(findPreference("fft_binning"))
        bindPreferenceSummaryToValue(findPreference("fft_blocksize"))
        bindPreferenceSummaryToValue(findPreference("display_logarithmic"))
        bindPreferenceSummaryToValue(findPreference("from_frequency"))
        bindPreferenceSummaryToValue(findPreference("till_frequency"))
        bindPreferenceSummaryToValue(findPreference("display_sample_numbers"))

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        if (id == android.R.id.home) {
            startActivity(Intent(activity, SettingsActivity::class.java))
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    companion object {

        /**
         * A preference value change listener that updates the preference's summary
         * to reflect its new value.
         */
        private val sBindPreferenceSummaryToValueListener =
            Preference.OnPreferenceChangeListener { preference, value ->
                val stringValue = value.toString()

                when (preference) {
                    is androidx.preference.ListPreference -> {
                        // For list preferences, look up the correct display value in
                        // the preference's 'entries' list.
                        val index = preference.findIndexOfValue(stringValue)

                        // Set the summary to reflect the new value.
                        preference.setSummary(
                            when {
                                index >= 0 -> preference.entries[index]
                                else -> "4096"
                            }
                        )
                    }

                    else -> preference.summary = stringValue
                }
                true
            }

        /**
         * Helper method to determine if the device has an extra-large screen. For
         * example, 10" tablets are extra-large.
         */
        private fun isXLargeTablet(context: Context): Boolean {
            return (context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE
        }

        /**
         * Binds a preference's summary to its value. More specifically, when the
         * preference's value is changed, its summary (line of text below the
         * preference title) is updated to reflect the value. The summary is also
         * immediately updated upon calling this method. The exact display format is
         * dependent on the type of preference.

         * @see .sBindPreferenceSummaryToValueListener
         */
        private fun bindPreferenceSummaryToValue(preference: Preference?) {

            if (preference == null) return

            // Set the listener to watch for value changes.
            preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener

            // Trigger the listener immediately with the preference's
            // current value.

            val sharedPreferences =
                PreferenceManager.getDefaultSharedPreferences(preference.context)

            // select the appropriate datatype
            val value = when (preference) {
                is ListPreference -> {
                    sharedPreferences.getString(preference.key, "")
                }

                is CheckBoxPreference -> {
                    sharedPreferences.getBoolean(preference.key, false)
                }

                is EditTextPreference -> {
                    sharedPreferences.getString(preference.key, "")
                }

                else -> throw Error("Introduced new type of preference ${preference.javaClass}, needs to be caught here")
            }

            // call change listener of the preference
            sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, value)

        }
    }

}